//
//  PictureSelectorViewController.swift
//  wbxm
//
//  Created by apple on 15/12/25.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

private let rowCount: CGFloat = 5
private let margin: CGFloat = 5
private let reuseIdentifier = "Cell"
private let maxImageCount = 9

class PictureSelectorViewController: UICollectionViewController {
    
    var imageList = [UIImage]()
    
    init() {
        //设置layout
        //1 计算每个cell的宽度
        let itemW = (screenW - (rowCount + 1) * margin) / rowCount
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        
        //设置组间距
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        
        super.init(collectionViewLayout: layout)
        //修改集合视图的背景颜色
        collectionView?.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

           // Register cell classes
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

       // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        
        let dalta = imageList.count == maxImageCount ? 0 : 1
        
        return imageList.count + dalta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
    
//        cell.backgroundColor = UIColor.randomeColor()
    
        //设置代理
        cell.delegata = self
  
        //设置数据源
        if indexPath.item == imageList.count {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
        
        return cell
    }
}
extension PictureSelectorViewController: PictureSelectorCellDelegate {
    func userWillChosePicture(cell: PictureSelectorCell) {
        print(__FUNCTION__)
        
        if cell.image != nil {
            print("不要再点了")
            return
        }
        
        //1得到图片选择器 控件
        let picker = UIImagePickerController()
        //modal出对应的图片选择器
        presentViewController(picker, animated: true, completion: nil)
        //询问用户访问权限 是iOS7之后 需要经过用户同意之后才能够获取用户个人隐私数据
        //2设置图片选择器的代理\
        //一旦指定了代理之后 就需要程序员手动dismiss picker
        picker.delegate = self
        
        //设置允许编辑 上传用户头像的时候 需要打开
//        picker.allowsEditing = true

    }
    
    func userWillDeletePicture(cell: PictureSelectorCell) {
        print(__FUNCTION__)
        //通过获取的cell 找到对应的indexPath
        if let index = collectionView?.indexPathForCell(cell) {
            //在数组中 删除对应的indexPath.item角标下的元素
            imageList.removeAtIndex(index.item)
            //操作完数据源 执行刷新
            collectionView?.reloadData()
        }
        
    }
}

extension PictureSelectorViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    //picker: 图片选择器本色
    //image: 表示用户选择的图片
    //editingInfo: 编辑信息
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        print("---")
        print(editingInfo)
        //将获取图片 添加到数组中  修改数组
        imageList.append(image)
        //刷新列表
        collectionView?.reloadData()
        //手动dismiss
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}


//----------------------------------------------
//1定义协议
@objc protocol PictureSelectorCellDelegate: NSObjectProtocol {
    //定义协议方法
    //添加图片
    optional func userWillChosePicture(cell: PictureSelectorCell)
    //删除图片 添加参数 把自己回掉回去
    optional func userWillDeletePicture(cell: PictureSelectorCell)
}


class PictureSelectorCell: UICollectionViewCell {
    
    @objc private func addBtnDidClick() {
        
        //使用代理调用协议方法  不能家!号  因为加了! 就必须要实现代理方法
        delegata?.userWillChosePicture?(self)
    }
    
    @objc private func deleteBtnDidClick() {
       
        delegata?.userWillDeletePicture?(self)
    }
    
    // MARK:定义外部模型属性
    
    var image: UIImage? {
        didSet {
            //如果设置的图片为空 就隐藏删除按钮
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: UIControlState.Normal)
        }
    }
    
    weak var delegata: PictureSelectorCellDelegate?
    
    // MARK:重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:设置页面和布局
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addBtn.snp_top)
            make.right.equalTo(addBtn.snp_right)
        }
        
        //绑定按钮的事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    // MARK:懒加载所有的子视图
    private lazy var deleteBtn: UIButton = UIButton(imageName: nil, backImageName: "compose_photo_close")
    private lazy var addBtn: UIButton = UIButton(imageName: nil, backImageName: "compose_pic_add")

    
}












